var jwt = require('jsonwebtoken');
var signkey = 'mes_qdhd_mobile_xhykjyxgs';



function randomString(len) {
    len = len || 32;
    var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
    var maxPos = $chars.length;
    var pwd = '';
    for (let i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}


exports.setToken = function(username){

    let randomID = randomString(32);
    return new Promise((resolve,reject)=>{
        const token = jwt.sign({
            name:username,
            _id:randomID
        },signkey,{ expiresIn:'2h' });
        resolve(token);
    })
}


exports.verToken = function(token){

    // console.log("src:"+ token);

    let bearer =  token.substr(0,6);
    // console.log(bearer);
    if ( bearer !== 'Bearer')
    {
        //不是Bearer 开头，手动添加上
        token = 'Bearer ' + token;
        // console.log("add:" + token);
    }

    // console.log("dst"+token);
    return new Promise((resolve,reject)=>{
        var info = jwt.verify(token.split(' ')[1],signkey);
        resolve(info);
    })
}
